<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" :rowKey="`id`" @loadData="loadData">
      <template #carSteward="{ record }">
        <a-link @click="onClickCarSteward(record)">
          {{ record.carHouseKeepName ? record.carHouseKeepName.split('、').slice(0, 3).join('、') : '未指派' }}
        </a-link>
        <a-button
          type="outline"
          size="mini"
          v-if="record.carHouseKeepName && record.carHouseKeepName.split('、').length > 3"
          @click="onClickCarSteward(record)"
        >
          查看更多
        </a-button>
      </template>
      <template #carTotalNum="{ record }">
        <a-link @click="toCarListFn(record)">{{ record.carNum }}</a-link>
      </template>
      <template #self-applet="{ record }">
        <div v-if="record.selfAppStatusName != null" class="flex items-center status-wrapper">
          <template v-if="!record.selfAppStatusName || record.selfAppStatusName == ''">
            <span :class="['close', 'status-icon']"></span>
            <span>禁用</span>
          </template>
          <template v-else>
            <span :class="[record.selfAppStatusName == '禁用' ? 'close' : 'open', 'status-icon']"></span>
            <span>{{ record.selfAppStatusName }}</span>
          </template>
        </div>
      </template>
      <template #store-status="{ record }">
        <div class="flex items-center status-wrapper">
          <span :class="[record.status == '20' ? 'close' : 'open', 'status-icon']"></span>
          <span>{{ record.statusName }}</span>
        </div>
      </template>
    </table-index>
    <CarButlerDialog ref="carButlerRef" @ok="handleOkCarButler" />
  </div>
</template>

<script setup name="StoreManageList">
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getSiteLeaseList, getSiteCity } from '@/api/asset/site'
  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import useNavigate from '@/hooks/useNavigate'
  import CarButlerDialog from './dialog/car-butler-dialog.vue'

  const { navigateTo } = useNavigate()
  const carsiteDict = usePageDict('carsiteDict')
  const router = useRouter()
  const carButlerRef = ref()

  const provinceList = ref([])
  // 获取筛选条件城市列表
  getSiteCity().then((res) => {
    if (res.code == 200) {
      const result = res.result
      provinceList.value = result.map((item) => {
        return {
          label: item.name,
          value: item.code,
        }
      })
    }
  })
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '门店名称', prop: 'siteNameLike', type: 'a-input' },
      {
        label: '城市',
        prop: 'cityCode',
        type: 'a-select',
        options: provinceList.value,
      },
      {
        label: '自营小程序',
        prop: 'selfAppStatus',
        type: 'a-select',
        options: carsiteDict.rentSiteSelfAppStatus,
      },
      {
        label: '门店车管家',
        prop: 'carHouseKeepId',
        type: 'remote-select',
        attrs: {
          type: 'driver_schedule_staff',
        },
      },
    ]
  })

  // 跳转到车辆列表页
  const toCarListFn = (record) => {
    router.push(`/assets/car/car-manage?siteId=${record.id}`)
  }

  // table 配置
  const table = useTable({
    columns: [
      { title: '门店名称', dataIndex: 'siteName', width: 150, fixed: 'left' },
      { title: '城市', dataIndex: 'cityName', width: 90 },
      { title: '门店地址', dataIndex: 'address' },
      { title: '门店状态', dataIndex: 'orderNo', slotName: 'store-status', width: 90 },
      {
        title: '门店车管家',
        dataIndex: 'carSteward',
        slotName: 'carSteward',
        titleTooltipContent: '工单开启车管家模式后，所有的长/短租订单由车管家针对交车人、换车人、还车人派单，相关负责人接单后，进行操作',
        width: 120,
      },
      { title: '门店车辆总数', dataIndex: 'carNum', slotName: 'carTotalNum', width: 90 },
      {
        title: '实时车辆出租率',
        dataIndex: 'carRentRate',
        render: (record) => {
          return record.carRentRate ? `${record.carRentRate}%` : '-'
        },
        titleTooltipContent: '门店现在车辆的实际出租率',
        width: 100,
      },
      {
        title: '明日预计车辆出租率',
        dataIndex: 'returnCarRate',
        render: (record) => {
          return record.returnCarRate ? `${record.returnCarRate}%` : '-'
        },
        titleTooltipContent: '门店预计明日车辆出租率（还车日期满24小时为100%出租率+超出24小时部分零散小时出租率）',
        width: 110,
      },
      {
        title: '今日交车订单数',
        dataIndex: 'giveCarRate',
        titleTooltipContent: '当前门店，所有订单预计用车时间为今日之和',
        width: 100,
      },
      {
        title: '今日还车订单数',
        dataIndex: 'returnCarDayRate',
        titleTooltipContent: '当前门店，所有订单预计还车时间为今日之和',
        width: 100,
      },
      { title: '自营小程序', dataIndex: 'selfAppStatus', slotName: 'self-applet', width: 100 },
    ],
    operates: [
      {
        label: '详情',
        permission: 'svms:merchant:store.view',
        method: (record) => {
          navigateTo('/merchant/store/detail/' + record.id, record.siteName + '-详情')
        },
      },
      {
        label: '编辑',
        permission: 'svms:merchant:store.edit',
        method: (record) => {
          navigateTo('/merchant/store/edit/' + record.id, record.siteName + '-编辑')
        },
      },
    ],
    buttons: [
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:merchant:store.add',
        method: () => {
          navigateTo('/merchant/store/create')
        },
      },
    ],
  })

  const onClickCarSteward = (record) => {
    record.carHousekeepList = JSON.parse(JSON.stringify(record.carHouseKeepIdList)) || []
    record.carHousekeepList.forEach((item) => {
      item.staffName = item.realname
      item.staffPhone = item.phone
      item.staffId = item.id
      item.staffStatusName = item.staffStatusName || undefined
    })
    while (record.carHousekeepList.length < 1) {
      record.carHousekeepList.push({ staffId: undefined })
    }
    carButlerRef.value.open(record)
  }

  const handleOkCarButler = () => {
    loadData()
  }

  // 接口参数（不包含page信息）
  const queryParam = reactive({})
  // 列表接口调用
  const loadData = (page) => {
    const fn = useFetchTableDataApi(table, queryParam, getSiteLeaseList)
    fn(page)
  }

  onMounted(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .status-wrapper {
    height: 28px;
    .status-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
    }
  }
</style>
